package com.kid.springcloud.controller;


import com.kid.springcloud.entity.Member;
import com.kid.springcloud.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Slf4j
public class MemberConsumerController {

//    定义MEMBER_SERVICE_PROVIDER_URL，作为基础地址
    public static final String MEMBER_SERVICE_PROVIDER_URL="http://MEMBER-SERVICE-PROVIDER";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/member/consumer/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("服务名为{}",service);
            List<ServiceInstance> instances = discoveryClient.getInstances(service);
            for (ServiceInstance instance : instances) {
                log.info("id={},host={},port={},uri={}",instance.getInstanceId(),instance.getHost(),instance.getPort(),instance.getUri());
            }
        }
        return discoveryClient;
    }
    @PostMapping("/member/consumer/save")
    public Result<Member> save(Member member){
        return restTemplate.postForObject(MEMBER_SERVICE_PROVIDER_URL+"/member/save",member,Result.class);
    }


    @GetMapping("/member/consumer/get/{id}")
    public Result<Member> getMemberById(@PathVariable("id") Long id){
        return restTemplate.getForObject(MEMBER_SERVICE_PROVIDER_URL+"/member/query/"+id,Result.class);
    }
}
